package com.itheima.web.servlet;

import com.itheima.pojo.User;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet{
    private UserServiceImpl service=new UserServiceImpl();
    //查询所有
    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("user selectAll");
    }

    //添加数据
    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("user add");
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("userName");
        String password=request.getParameter("password");
        //获取复选框数据
        String remember=request.getParameter("remember");
//        System.out.println(username);
        //2.调用service查询
        User user=service.login(username,password);
//        response.setContentType("text/html;charset=utf-8");

        //3.判断user是否为null
        if(user!=null){
            //跳转到selectAllServlet
            //判断用户是否记住密码
            if("1".equals(remember)){
                //创建cookie对象
                Cookie c_username=new Cookie("username",username);
                Cookie c_pwd=new Cookie("password",password);
                //持久化存储,7天
                c_username.setMaxAge(60*60*24*7);
                c_pwd.setMaxAge(60*60*24*7);
                //发送
                response.addCookie(c_username);
                response.addCookie(c_pwd);
            }
            //将登录成功后的user对象存储到session
            HttpSession session=request.getSession();
            session.setAttribute("User",user);
            String contextPath = request.getContextPath();

            //重定向
            response.sendRedirect(contextPath+"/brand.html");
        }else{
            //存储错误信息到requset
            request.setAttribute("login_msg","用户名或密码错误");
            response.setContentType("text/html;charset=utf-8");
            //响应失败的标识
            response.getWriter().write("unsuccessful");
            //跳转到login.html
            request.getRequestDispatcher("/login.html").forward(request,response);//request.getRequestDispatcher("...")转发后路径会改变
        }
    }
}
